import { Ref, ref, watchPostEffect } from "vue"
import { dividerHeight, wapperHeight, resumePageHeight } from "./HTMLRender.helpers"

type PageInfo = {
  top: number,
  height: number
}
export const usePageState = (html: Ref<string>) => {
  const viewRef = ref<HTMLDivElement>()

  const wapperHeightRef = ref(0)
  const pageInfosRef = ref<PageInfo[]>([])

  watchPostEffect(() => {
    if (!html.value || !viewRef.value) return
    const pageCount = Math.ceil(viewRef.value.scrollHeight / resumePageHeight)
    wapperHeightRef.value = pageCount * wapperHeight + (pageCount - 1) * dividerHeight

    const childDom = Array.from(viewRef.value.querySelectorAll<HTMLElement>('*'))

    const domsPos = childDom
      .filter((item) => {
        if (!item.children.length || item.nodeName == 'Li') {
          return true
        } else {
          return false
        }
      })
      .map((item) => {
        return {
          start: item.offsetTop,
          end: item.offsetTop + item.offsetHeight,
          dom: item
        }
      })

    const newPageInfos: PageInfo[] = []
    let prevPosY = 0
    let domsPosIndex = 0

    while (newPageInfos.length < pageCount) {
      let currentY = prevPosY + resumePageHeight

      for (let i = domsPosIndex; i < domsPos.length; i++) {
        const pos = domsPos[i] || {}

        if (pos.start <= currentY && currentY <= pos.end) {
          domsPosIndex = i
          currentY = currentY - (currentY - pos.start)
        }

        if (pos.start > currentY && pos.end > currentY) {
          break;
        }

      }

      newPageInfos.push({ top: prevPosY, height: currentY - prevPosY })
      prevPosY = currentY
    }

    pageInfosRef.value = newPageInfos
  })

  return {
    viewRef,
    wapperHeightRef,
    pageInfosRef
  }
}